package com.zhouixi.interceptor;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;

// WebSocket认证拦截器
@Component
public class AuthInterceptor implements HandshakeInterceptor {


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, org.springframework.web.socket.WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 从请求参数或Header获取Token
        String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter("token");
        if (token == null || !validateToken(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return false; // 认证失败，拒绝连接
        }
        // 从Token解析userId并存入属性
        String userId = parseUserIdFromToken(token);
        attributes.put("userId", userId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, org.springframework.web.socket.WebSocketHandler wsHandler, Exception exception) {

    }

    private boolean validateToken(String token) {
        // 实现Token校验逻辑（如JWT验证）
        return true;
    }

    private String parseUserIdFromToken(String token) {
        // 从Token中解析userId
        return "解析出的用户ID";
    }
}